<?php

/**
 * Menashop
 *
 * LICENSE
 *
 * This source file is subject to the license that is bundled
 * with this project in the file LICENSE.txt
 *
 * @category   Menashop
 * @package    Menashop_Downloader
 * @copyright  Copyright (c) 2011 Menashop UA Inc. (http://www.menashop.com.ua)
 * @license    LICENSE.txt
 * @version    1.0.0
 * @since      File available since Release 1.0.0
 */

/**
 * The downloader
 * 
 * @category   Menashop
 * @package    Menashop_Downloader
 * @copyright  Copyright (c) 2011 Menashop UA Inc. (http://www.menashop.com.ua)
 * @license    LICENSE.txt
 */
class Menashop_Downloader
{

    /**
     * The logger
     * @var object 
     */
    protected $_logger;

    /**
     * Initializate the downloader
     */
    public function __construct()
    {
        $this->_logger = Zend_Registry::get('log');
    }

    /**
     * Download amd gunzip file
     * @param string $url
     * @param string $destPath 
     * @return boolean
     */
    public function downloadAndUnpackGzFile($url, $destPath)
    {
        $result = true;
        // try to download file
        if (!$this->downloadFile($url, $destPath)) {
            $result = false;
        } else {
            // unpack file
            exec("gunzip -f $destPath", $output, $return_var);
            if ($return_var == 0) {
                $filename = preg_replace('/\.gz$/', '', $destPath);
                // check result file
                if (!file_exists($filename) || !filesize($filename)) {
                    $this->_logger->crit(__METHOD__ . " can't gunzip file $destPath");
                    $result = false;
                }
            }
        }
        return $result;
    }

    /**
     * Download file
     * @param string $url
     * @param string $destPath
     * @return boolean 
     */
    public function downloadFile($url, $destPath)
    {
        $result = true;
        $this->_logger->debug(__METHOD__ . " started download of file from $url to $destPath");
        // try to download file
        if (!copy($url, $destPath)) {
            $this->_logger->crit(__METHOD__ . " can't download file from $url to $destPath");
            $result = false;
        }
        return $result;
    }

}

